
package com.zkmonitor.interceptor;

import com.zkmonitor.common.LoginRequired;
import com.zkmonitor.common.UserHolder;
import com.zkmonitor.exception.ShepherException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginRequiredInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = LoggerFactory.getLogger(LoginRequiredInterceptor.class);

    @Autowired
    private UserHolder userHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    	request.setCharacterEncoding("UTF-8");
        String url = request.getServletPath();    
        log.info("post URL："+url);
        
     // 获取当前登录人信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if ((handlerMethod.getBeanType().isAnnotationPresent(LoginRequired.class) ||
                    handlerMethod.getMethodAnnotation(LoginRequired.class) != null) &&
                    userHolder.getUser() == null) {
                throw ShepherException.createNoLoginException();
            }
        }

        return true;
    }

   
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

}
